package uk.ac.uea.wolfie;

import java.sql.*;

public class STSWebService
{

	public String getToken(String inputToken)
	{

		if( validateOAuthToken(inputToken) )
		{
			// extract the external system id and username from the token
			int externalSystemID = 1;

			String externalSystemUserID = "abc";
			
			// lookup the UEA id
			String ueaID = reverseLookUpExternalSystemID( externalSystemID, externalSystemUserID );

			// generate the return token
			return generateWSTrustToken(ueaID);
		}
		else
		{
			return "<error>Invalid token</error>";		
		}
	}
	
	private boolean validateOAuthToken(String oAuthToken)
	{
		return true;
	}
	
	private String reverseLookUpExternalSystemID(int externalSystemID,String externalSystemUserID)
	{
		try
		{
			// This will load the MySQL driver, each DB has its own driver
			Class.forName("com.mysql.jdbc.Driver");
			
			String dbURL = "jdbc:mysql://ueaweb18.uea.ac.uk/wolfie?user=wolfie&password=B00kOfFace";
			// Setup the connection with the DB
			Connection connect = DriverManager.getConnection(dbURL);
			Statement statement = connect.createStatement();
			String sql =
					"SELECT username "+
					"FROM external_user " +
					" INNER JOIN login ON login.login_id = external_user.login_id " +
					"WHERE external_system_login = '"+externalSystemUserID.replaceAll("'", "''")+"'"+
					" AND external_system_id = "+externalSystemID;
			ResultSet resultSet = statement.executeQuery( sql );
			while (resultSet.next())
			{
				// get the loginID
				String loginID = resultSet.getString("username");
				
				// close connections
				resultSet.close();
				statement.close();
				connect.close();
				
				return loginID;
			}
//			https://ueaweb18.uea.ac.uk:2087/3rdparty/phpMyAdmin/index.php?db=wolfie&token=2c83b91da0f1101aa90b795536ee9213
		}
		catch (ClassNotFoundException cnfe)
		{
			cnfe.printStackTrace();			
		}
		catch (SQLException sqle)
		{
			sqle.printStackTrace();
		}
		return "";		
	}
	
	private String generateWSTrustToken(String ueaID)
	{
		return "";
	}	

	public static void main(String[]argv)
	{
		STSWebService webservice = new STSWebService();
		System.out.println(webservice.reverseLookUpExternalSystemID(1,"505016383"));
		System.out.println("End");
	}
}